package com.xzq.bugstack.client;

import com.xzq.bugstack.util.MsgUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 14:20
 * @Version 1.0.0
 **/
public class NettyClient {
    public static void main(String[] args) {
        new NettyClient().connect("127.0.0.1", 9999);
    }

    private void connect(String host, int port) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ChannelFuture f = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyChannelInitializer())
                    .connect(host, port).sync();
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo1"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo2"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo3"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo4"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo5"));
            f.channel().writeAndFlush(MsgUtil.buildMsg(f.channel().id().toString(), "我是MsgInfo6"));

            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
